package com.longling.hayarider.activity;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

/**
 * @ClassName PermissionCheckPepsi
 * @Description TODO
 * @date 2021-07-14 16:35
 * @Company LongLing
 * @Version 1.0
 * @Author 潇妙
 */
public abstract class PermissionCheckPepsi extends AppCompatActivity {
    private  ICheckPermission mICheckPermission = null;

    public interface ICheckPermission {
        void onAllow();

        void onReject();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    public void checkPermission(String[] permission, ICheckPermission iCheckPermission) {
        if (Build.VERSION.SDK_INT < 23 || permission.length == 0) {
            if (iCheckPermission != null){
                iCheckPermission.onAllow();
            }
        }else {
            if (iCheckPermission != null){
                mICheckPermission = iCheckPermission;
                ActivityCompat.requestPermissions(this,permission,0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mICheckPermission != null && requestCode == 0){
            for (int i = 0; i < grantResults.length; i++) {
                //判断权限是否被允许，只要又一次拒绝就算失败
                if (grantResults[i] == PackageManager.PERMISSION_DENIED){
                    // 1：用户拒绝了该权限，没有勾选"不再提醒"，此方法将返回true。
                    // 2：用户拒绝了该权限，有勾选"不再提醒"，此方法将返回 false。
                    // 3：如果用户同意了权限，此方法返回false
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this,permissions[i])){
                        Toast.makeText(this, "你已拒绝此权限，如果需要，可以在设置中打开此权限", Toast.LENGTH_SHORT).show();
                    }else {
                        mICheckPermission.onReject();
                    }
                    return;
                }
            }
            mICheckPermission.onAllow();
        }
    }
}
